package com.leetcode.根据算法进行分类.单调栈相关;

import java.util.ArrayDeque;

/**
 * @author: ZhouBert
 * @date: 2021/4/1
 * @description: 1006. 笨阶乘
 * https://leetcode-cn.com/problems/clumsy-factorial/
 */
public class B_1006_笨阶乘 {

	static B_1006_笨阶乘 action = new B_1006_笨阶乘();

	public static void main(String[] args) {
		test1();
	}

	static void test1() {
		int res = action.clumsy(4);
		System.out.println("res = " + res);
	}


	/**
	 * 固定顺序：* / + -
	 * 根据模拟的规则：
	 * 1.做一个双端队列，每次见到 * / 就计算；
	 * 2.全部计算完毕以后，再从队列头开始计算 + -
	 *
	 * @param N
	 * @return
	 */
	public int clumsy(int N) {
		char[] cals = new char[]{'*', '/', '+', '-'};
		int cIndex = 0;
		ArrayDeque<Integer> numsDeque = new ArrayDeque<>();
		ArrayDeque<Character> charactersDeque = new ArrayDeque<>();
		numsDeque.addLast(N);
		for (int i = N - 1; i > 0; i--) {
			if (cIndex == 2 || cIndex == 3) {
				charactersDeque.addLast(cals[cIndex]);
				numsDeque.addLast(i);
			} else {
				int tempValue = 0;
				//此时 cDeque 不为空 && 符号优先计算
				switch (cals[cIndex]) {
					case '*':
						tempValue = numsDeque.removeLast() * i;
						break;
					default:
						tempValue = numsDeque.removeLast() / i;
						break;
				}
				numsDeque.addLast(tempValue);
			}
			if (cIndex == 3) {
				cIndex = 0;
			} else {
				cIndex++;
			}

		}
		int first = numsDeque.removeFirst();
		//此时已经计算完 * /
		while (!charactersDeque.isEmpty()) {
			int second = numsDeque.removeFirst();
			char c = charactersDeque.removeFirst();
			switch (c) {
				case '+':
					first = first + second;
					break;
				default:
					first = first - second;
					break;
			}
		}
		return first;
	}
}
